var myExt_urlBarListener = {
  QueryInterface: function(aIID)
  {
   if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
       aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
       aIID.equals(Components.interfaces.nsISupports))
     return this;
   throw Components.results.NS_NOINTERFACE;
  },

  onLocationChange: function(aProgress, aRequest, aURI)
  {
    myExtension.processNewURL(aURI);
  },

  onStateChange: function(a, b, c, d) {},
  onProgressChange: function(a, b, c, d, e, f) {},
  onStatusChange: function(a, b, c, d) {},
  onSecurityChange: function(a, b, c) {}
};

var myExtension = {
  oldURL: null,
  average: null,
  
  init: function() {
    // Listen for webpage loads
    gBrowser.addProgressListener(myExt_urlBarListener,
        Components.interfaces.nsIWebProgress.NOTIFY_LOCATION);
  },
  
  uninit: function() {
    gBrowser.removeProgressListener(myExt_urlBarListener);
  },

  processNewURL: function(aURI) {
	var tinyURL = getURL(aURI.spec);
    if (tinyURL == this.oldURL)
      return;
    
    // now we know the url is new...
	try {
		
		this.average = 0;
		
		var xmlhttp = XMLHttpRequest();
                xmlhttp.open("GET", "http://localhost:1251/Download/site.xml", false);
                xmlhttp.send(null);
                xmlDoc = xmlhttp.responseXML;
				aux = xmlDoc.getElementsByTagName("grade");
				for (i=0; i<aux.length; i++) {
					site = aux[i].getElementsByTagName("site")[0].firstChild.nodeValue;
					if (tinyURL == site) {
						this.average = aux[i].getElementsByTagName("average")[0].firstChild.nodeValue;
					}
				}
				
        } catch (e) {
                Components.utils.reportError(e);
        }
    this.oldURL = tinyURL;
  }
};

window.addEventListener("load", function() {myExtension.init()}, false);
window.addEventListener("unload", function() {myExtension.uninit()}, false);